package com.basic.modules.sys.controller;

import  com.basic.common.exception.RRException;
import com.basic.common.utils.R;
import com.basic.modules.oss.cloud.OSSFactory;
import com.basic.modules.sys.entity.SysFileEntity;
import com.basic.modules.sys.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/sys/file")
public class SysFileController {

    @Autowired
    private SysFileService sysFileService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ResponseBody
    public R uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //上传文件
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix,"");
        //保存文件信息
        SysFileEntity saveFile = new SysFileEntity();
        saveFile.setFileName(originalFilename);
        saveFile.setFileType(suffix);
        saveFile.setFileUrl(url);
        saveFile.setFileSize(new BigDecimal(size));
        sysFileService.save(saveFile);
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        map.put("fileId", saveFile.getFileId());
        map.put("fileSize", saveFile.getFileSize());
        map.put("fileName", saveFile.getFileName());
        return R.ok(map);
    }
}
